package org.apache.skywalking.apm.plugin.kepler.utils;

import com.github.difflib.DiffUtils;
import com.github.difflib.UnifiedDiffUtils;
import com.github.difflib.patch.Patch;
import com.xiaomaoguai.fcp.pre.kepler.common.utils.JsonUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author WeiHui-Z
 * @version v1.0.0
 * @date 2019/6/7 11:40
 * @since JDK 1.8
 */
public class WrapperDiffUtils {

	public static String getDiff(String afterJson, String beforeJson) throws com.github.difflib.algorithm.DiffException {
		List<String> originalStrings = Arrays.asList(beforeJson.split("\r\n"));
		List<String> revisedStrings = Arrays.asList(afterJson.split("\r\n"));
		Patch<String> patch = DiffUtils.diff(originalStrings, revisedStrings);
		List<String> unifiedDiff = UnifiedDiffUtils.generateUnifiedDiff("beforeConvert", "afterConvert", originalStrings, patch, 0);
		unifiedDiff.add(0, "diff --git");

		StringBuilder sb = new StringBuilder();
		unifiedDiff.forEach(v -> {
			sb.append(v);
			sb.append("\n");
		});
		return JsonUtils.toFormatJsonString(sb.toString());
	}

}
